﻿var daysOfWeek = ["Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"];
var months = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"];

function baseViewModel() {

    var self = this;

    self.routingPattern = "{0}\\{1}"; //{ViewModelMethod}\{ParameterObject}
    self.defaultCommand = "page"; //  
    self.faculties = ko.observableArray([]);
    self.courses = ko.observableArray([]);
    self.groups = ko.observableArray([]);
    self.tutorials = ko.observableArray([]);
    self.tutorialTypes = ko.observableArray([]);
    self.isLoading = ko.observable(false);
    self.currentDay = ko.observable(new Date());
    self.weekDayDates = ko.observable([]);
    self.times = ko.observableArray([]);
    self.selectedScheduleCard = ko.observable();
    self.schedule = ko.observableArray([]);
    
    self.hasHash = function() {
        return typeof window.location.hash !== undefined && window.location.hash != "";
    };
    
    self.pushHashCommand = function (command) {
        var url = window.location.href.replace(/#.*/, '');

        window.location.href = url + '#' + command;
    };

    // Обработчик url-команд
    this.hashCommandHadler = function (loc) {
        if (typeof loc !== 'undefined') {
            var url = loc.href.replace(/^.*#/, '');
            var command = url.split('\\');

            if (typeof (command[0]) !== "undefined" && command[0] != "") {
                this[command[0]](command);
            } else {
                this[this.defaultCommand](command);
            }
        }
    };

    self.updateWeekDays = function() {
        var ar = [];
        var ticksInDay = 86400000;

        for (var i = 0; i <= 5; i++) {

            var day = new Date(self.currentDay() - (self.currentDay().getDay() - 1) * ticksInDay + i * ticksInDay);

            ar[i] = {
                date: daysOfWeek[i] // + ", " + day.getDate() + " " + months[day.getMonth()] + " " + day.getFullYear() + " г."
            };
        }

        self.weekDayDates(ar);
    };

    self.showError = function (msg) {
        $.jGrowl("<b><span style='color: #f00;'>"+msg+"</span></b>", { header: "<b><span style='color: #f00;'>Ошибка</span></b>", position: "center" });
    };

    // push 7 days from current day 
    this.backWeek = function () {
        self.currentDay().setDate(self.currentDay().getDate() - 7);

        self.updateWeekDays();

        self.loadData({
            address: "schedule/get",
            params: { 'groupId': self.currentGroup() },
            onsuccess: function (data) {
                applySchedule(data);
            },
            onerror: function (x, h, r) {
            }
        });
    };

    // add 7 days to current day
    self.forwardWeek = function () {
        self.currentDay().setDate(self.currentDay().getDate() + 7);

        self.updateWeekDays();

        self.loadData({
            address: "schedule/get",
            params: { 'groupId': self.currentGroup() },
            onsuccess: function (data) {
                applySchedule(data);
            },
            onerror: function (x, h, r) {
            }
        });
    };

    // set current day today
    self.todayWeek = function () {
        self.currentDay(new Date());

        self.updateWeekDays();
    };

    self.loadData = function(arg) {
        ko.dependentObservable(function() {

            self.isLoading(true);

            $.ajax({
                    type: 'GET',
                    url: '/api/v1.0/' + arg.address,
                    data: arg.params,
                    success: function(data) {
                        if (arg.onbefore !== undefined)
                            arg.onbefore();

                        if (arg.obj !== undefined) {
                            arg.obj([]);
                            $.each(data, function(index, item) {
                                arg.obj.push(item);
                            });
                        }

                        if (arg.onsuccess !== undefined)
                            arg.onsuccess(data);

                        self.isLoading(false);
                    },
                    error: function(x, h, r) {
                        if (arg.onerror !== undefined)
                            arg.onerror(x, h, r);
                        else
                            self.showError("Возникла ошибка!");

                        self.isLoading(false);
                    }
                });

            if (arg.after !== undefined)
                arg.after();

        }, this);
    };

    self.sendData = function (arg) {
        self.isLoading(true);

        if (arg.onbefore !== undefined)
            arg.onbefore(obj);

        $.ajax({
            type: 'POST',
            url: '/api/v1.0/' + arg.address,
            data: arg.params,
            success: function (data) {

                if (arg.onsuccess !== undefined)
                    arg.onsuccess(data);

                self.isLoading(false);
            },
            error: function () {
                if (arg.onerror !== undefined)
                    arg.onerror(x, h, r);
                else
                    self.showError("Возникла ошибка!");

                self.isLoading(false);
            }
        });
    };

    self.deleteData = function(arg) {
        self.isLoading(true);

        if (arg.onbefore !== undefined)
            arg.onbefore(obj);

        $.ajax({
                type: 'Delete',
                url: '/api/v1.0/' + arg.address,
                data: arg.params,
                success: function() {

                    if (arg.onsuccess !== undefined)
                        arg.onsuccess();

                    self.isLoading(false);
                },
                error: function() {
                    if (arg.onerror !== undefined)
                        arg.onerror(x, h, r);
                    else
                        self.showError("Возникла ошибка!");

                    self.isLoading(false);
                }
            });
    };

    self.deselectAll = function () {
        if (document.selection) {
            document.selection.empty();
        } else if (window.getSelection) {
            window.getSelection().removeAllRanges();
        }
    };

    self.init = function() {
        var localThis = this;

        if (self.hasHash()) {
            self.hashCommandHadler.call(this, window.location);
        }

        $(window).bind('hashchange', function(obj) {
            self.hashCommandHadler.call(localThis, obj.currentTarget.location);
        });

        self.loadData({
            address: "faculty/getall",
            obj: self.faculties,
        });
        self.loadData({
            address: "course/getall",
            obj: self.courses,
        });

        self.loadData({
            address: "time/getall",
            obj: self.times
        });

        self.loadData({
            address: "tutorial/getall",
            obj: self.tutorials
        });

        self.loadData({
            address: "tutorialtype/getall",
            obj: self.tutorialTypes
        });

        //$(".splitter").jqxSplitter();


    };
}

function extend(child, parent) {
    if (typeof (parent) == "function")
        child.constructor.prototype = new parent();
    else
        child.constructor.prototype = parent;
    child.prototype = child.__proto__ = child.constructor.prototype;
};